package de.tc.stammdatenverwaltung.gui;

import de.tc.stammdatenverwaltung.functions.PropertiesHandler;
import de.tc.stammdatenverwaltung.mailing.MailConfig;
import de.tc.stammdatenverwaltung.functions.commonFunctions;
import de.tc.stammdatenverwaltung.functions.myMainTableModel;
import de.tc.stammdatenverwaltung.gui.kontakthistory.Kontakthistorie;
import de.tc.stammdatenverwaltung.mailing.mailEditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;


public class Main extends javax.swing.JFrame {

    //eine Connection ist genug, wiederverwenden!
    public static Connection con;

    private Kontakt k = null;

    public static int selectedElement = 0;

    //template fuer die query, kommt bestenfalls noch ein where dran
    public static String selectSQL =
    //feldreihnfolg aendern
    "select s.ID, 0 MAILAN, s.ANREDE, s.TITEL, s.VNAME, s.NAME2, s.NNAME, s.NICK, " +
    "s.GEBURTSTAG, iif (s.GEBURTSTAG is not null, F_GFORMATD('dd.mm.yyyy', GEBURTSTAG), '') BDAY2, " +
    "s.ANSCHRIFT, s.PLZ_ORT, s.TEL, s.FAX, s.MOBIL, s.MAIL1, s.MAIL2, s.ABITUR, " +
    "iif (s.ABITUR is not null, F_GFORMATD('yyyy', ABITUR), '') ABI2, s.AEMTER, s.VEREIN, " +
    "s.TAGFIELD, s.FIRMA, s.RANG, s.BERUF, s.F_ANSCHRIFT, s.F_PLZ_ORT, s.F_TEL, s.F_FAX, s.F_MAIL " +
    "from stammdaten s ";
    public static String order = " order by nname asc, vname asc";

    //private String pfad = "tc_stammdaten";
    public static myMainTableModel mtm = null;

    private boolean testeVerbindung()
    {
      PropertiesHandler ph = new PropertiesHandler();
      String host = ph.getProperty("db-server"),
             port = ph.getProperty("db-port"),
             user = ph.getProperty("db-user"),
             path = ph.getProperty("db-path"),
             pass = ph.getProperty("db-pass");
      try
      {
        DriverManager.class.forName("org.firebirdsql.jdbc.FBDriver");
        Connection con2 = DriverManager.getConnection( "jdbc:firebirdsql:" + host + "/" + port + ":" + path + "?charSet=UTF-8",
                user, pass );
        con2.close();
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }
    }

    public Main() {
      try
      {
        boolean retry = true;
        while ( retry && !testeVerbindung() )
        {
          retry = ( JOptionPane.showConfirmDialog(this, "Fehler beim Verbinden mit der Datenbank, wollen Sie " +
                      "die Einstellungen bearbeiten?", "Fehler", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE)
                    == JOptionPane.YES_OPTION);

          if (retry)
          {
            DatabaseConfig dbc = new DatabaseConfig(null, true);
            dbc.onStart = true;
            dbc.setVisible(true);
            dbc.dispose();
          }
        }
        PropertiesHandler ph = new PropertiesHandler();
        DriverManager.class.forName("org.firebirdsql.jdbc.FBDriver");

        String host = ph.getProperty("db-server"),
             port = ph.getProperty("db-port"),
             user = ph.getProperty("db-user"),
             path = ph.getProperty("db-path"),
             pass = ph.getProperty("db-pass");

        con = DriverManager.getConnection( "jdbc:firebirdsql:" + host + "/" + port + ":" + path + "?charSet=UTF-8",
                user, pass );
      }
      catch (Exception ex)
      {
        JOptionPane.showMessageDialog(null, "Es kann keine Verbindung zur Datenbank hergestellt werden! Fehler:\r\n" +
          ex.getLocalizedMessage(), "Fehler!", 1);
        ex.printStackTrace();
        System.exit(1);
      }

      //das hier raus, damit wir nur laden, wenn wir die DB auch finden
      initComponents();

      this.setExtendedState(JFrame.MAXIMIZED_BOTH); //Fenster maximieren
      jPanel1.setSize(100, jPanel1.getWidth());

      mtm = new myMainTableModel();
      jTable1.setModel(mtm);
      jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

      jScrollPane1.setViewportView(jTable1);
      commonFunctions.load_query_to_table(selectSQL + order, jTable1, mtm);

      this.setTitle("Stammdatenverwaltung für den TC Leipzig");

      if (jTable1.getRowCount() > selectedElement)
        jTable1.setEditingRow(selectedElement);

      jTable1.requestFocus();
    }

    private void oeffneKontakt(String art, Integer pos)
    {
                            //parent, modal, custom ...
      k = new Kontakt(this, false, art, pos.intValue());

      //die Action vom speichern/anlegen
      k.jButton3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
          if (k.art.equalsIgnoreCase("Neu"))
            k.mkInsert();
          else
            if (k.art.equalsIgnoreCase("edit"))
              k.mkUpdate();

          commonFunctions.load_query_to_table(selectSQL + order, jTable1, mtm);
        }
      });

      //die Action vom löschen
      k.jButton5.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
          if (JOptionPane.showConfirmDialog(null, "Kontakt wirklich löschen?",
              "Sicherheitsfrage:", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
          {
            String deleteQ = "delete from stammdaten where id = " + k.ID;
            try
            {
              Statement stmt = Main.con.createStatement();
              stmt.executeUpdate(deleteQ);

              //element aus der liste entfernen
              int el = commonFunctions.markedElement.indexOf(k.ID);
              commonFunctions.markedElement.remove(el);

              boolean goOn = true;

              if ( el < commonFunctions.markedElement.size())
                //ID auf das nächste element (rutscht eins nach utnen!) setzen
                k.ID = commonFunctions.markedElement.get(el);
              else if (commonFunctions.markedElement.size() > 0)
                //wenn wir das bisher letzte element gelöscht haben, dann das neue letzte nehmen
                k.ID = commonFunctions.markedElement.get(el - 1);
              else
                //wenn wir das letzte Element gelöscht haben
                goOn = false;

              JOptionPane.showMessageDialog(k, "Kontakt gelöscht!", "Hinweis", JOptionPane.INFORMATION_MESSAGE);
              if (goOn)
                k.loadData();
              else
                k.closeKontaktWindow();
            }
            catch (SQLException sqle)
            {
              JOptionPane.showMessageDialog(null, "Beim Ausführen der Abfrage ist ein Fehler aufgetreten - Abfrage:\r\n” " +
                deleteQ + "\r\n+Fehler:\r\n" + sqle.getLocalizedMessage(), "Fehler!", 1);
              sqle.printStackTrace();
            }
          }
          commonFunctions.load_query_to_table(selectSQL + order, jTable1, mtm);
        }
      });
      k.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton9 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton10 = new javax.swing.JButton();
    jButton11 = new javax.swing.JButton();
    jButton7 = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();
    jButton8 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jPanel2 = new javax.swing.JPanel();
    jPanel7 = new javax.swing.JPanel();
    jCheckBox28 = new javax.swing.JCheckBox();
    jCheckBox29 = new javax.swing.JCheckBox();
    jCheckBox30 = new javax.swing.JCheckBox();
    jCheckBox31 = new javax.swing.JCheckBox();
    jCheckBox32 = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jMenuItem3 = new javax.swing.JMenuItem();
    jMenuItem2 = new javax.swing.JMenuItem();
    jMenuItem1 = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowOpened(java.awt.event.WindowEvent evt) {
        formWindowOpened(evt);
      }
    });

    jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    jPanel1.setMinimumSize(new java.awt.Dimension(0, 70));

    jButton1.setText("Kontakt anlegen");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });

    jButton2.setText("Kontakt bearbeiten");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
      }
    });

    jButton3.setText("Kontakt anzeigen");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton3ActionPerformed(evt);
      }
    });

    jButton9.setText("Inhalt filtern ...");
    jButton9.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton9ActionPerformed(evt);
      }
    });

    jButton4.setText("Daten exportieren");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton4ActionPerformed(evt);
      }
    });

    jButton5.setText("Daten importieren");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton5ActionPerformed(evt);
      }
    });

    jButton6.setText("Schreibe E-Mail");
    jButton6.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton6ActionPerformed(evt);
      }
    });

    jButton10.setText("Markierung aufheben");
    jButton10.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton10ActionPerformed(evt);
      }
    });

    jButton11.setText("Kommunikation zeigen");
    jButton11.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton11ActionPerformed(evt);
      }
    });

    jButton7.setText("Versionen...");
    jButton7.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton7ActionPerformed(evt);
      }
    });

    jButton8.setText("Alle markieren");
    jButton8.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton8ActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jButton11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jButton8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGap(6, 6, 6)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jButton9, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
            .addGap(9, 9, 9)
            .addComponent(jButton4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton5))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jButton10)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 322, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(jLabel1)
              .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton7)))
        .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jButton2)
            .addGap(6, 6, 6)
            .addComponent(jButton6))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jButton1)
              .addComponent(jButton3)
              .addComponent(jButton5)
              .addComponent(jButton4)
              .addComponent(jButton9))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                  .addComponent(jButton11)
                  .addComponent(jButton8)
                  .addComponent(jButton7)
                  .addComponent(jButton10)))
              .addGroup(jPanel1Layout.createSequentialGroup()
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)))))
        .addContainerGap())
    );

    jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

    jCheckBox28.setText("Forum Thomanum");
    jCheckBox28.setEnabled(false);

    jCheckBox29.setText("Förderkreis Thomanerchor");
    jCheckBox29.setEnabled(false);

    jCheckBox30.setText("Thomanerbund");
    jCheckBox30.setEnabled(false);

    jCheckBox31.setText("Freund des Chores");
    jCheckBox31.setEnabled(false);

    jCheckBox32.setText("Alumnus");
    jCheckBox32.setEnabled(false);

    javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
    jPanel7.setLayout(jPanel7Layout);
    jPanel7Layout.setHorizontalGroup(
      jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 915, Short.MAX_VALUE)
      .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel7Layout.createSequentialGroup()
          .addContainerGap()
          .addComponent(jCheckBox28)
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addComponent(jCheckBox29)
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addComponent(jCheckBox30)
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addComponent(jCheckBox31)
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addComponent(jCheckBox32)
          .addContainerGap(168, Short.MAX_VALUE)))
    );
    jPanel7Layout.setVerticalGroup(
      jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 36, Short.MAX_VALUE)
      .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel7Layout.createSequentialGroup()
          .addGap(1, 1, 1)
          .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(jCheckBox28)
            .addComponent(jCheckBox29)
            .addComponent(jCheckBox30)
            .addComponent(jCheckBox31)
            .addComponent(jCheckBox32))
          .addContainerGap(12, Short.MAX_VALUE)))
    );

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel2Layout.createSequentialGroup()
        .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGap(305, 305, 305))
    );
    jPanel2Layout.setVerticalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    jTable1.setAutoCreateRowSorter(true);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {
        {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
        {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null}
      },
      new String [] {
        "Titel 1", "Titel 2", "Titel 3", "Titel 4", "Titel 5", "Titel 6", "Titel 7", "Titel 8", "Titel 9", "Titel 10", "Titel 11", "Titel 12", "Titel 13", "Titel 14", "Titel 15", "Titel 16", "Titel 17", "Titel 18", "Titel 19", "Titel 20", "Titel 21", "Titel 22"
      }
    ));
    jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
    jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    jTable1.setDoubleBuffered(true);
    jTable1.setDragEnabled(true);
    jTable1.setFillsViewportHeight(true);

    org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jScrollPane1, org.jdesktop.beansbinding.ELProperty.create("${preferredSize}"), jTable1, org.jdesktop.beansbinding.BeanProperty.create("minimumSize"));
    bindingGroup.addBinding(binding);

    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jTable1MouseClicked(evt);
      }
    });
    jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jTable1KeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jTable1KeyReleased(evt);
      }
    });
    jScrollPane1.setViewportView(jTable1);

    jMenu1.setLabel("Datei");

    jMenuItem3.setText("Datenbank Konfigurieren");
    jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jMenuItem3ActionPerformed(evt);
      }
    });
    jMenu1.add(jMenuItem3);

    jMenuItem2.setText("E-Mail Konfigurieren");
    jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jMenuItem2ActionPerformed(evt);
      }
    });
    jMenu1.add(jMenuItem2);

    jMenuItem1.setText("Beenden");
    jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jMenuItem1ActionPerformed(evt);
      }
    });
    jMenu1.add(jMenuItem1);

    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1224, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    bindingGroup.bind();

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem1ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem1ActionPerformed
      System.exit(0);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
      oeffneKontakt("neu", -1);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
    {//GEN-HEADEREND:event_jButton2ActionPerformed
      try
      {
        oeffneKontakt("edit", commonFunctions.markedElement.elementAt(jTable1.getSelectedRow()) );
      }
      catch (ArrayIndexOutOfBoundsException ex)
      {
        JOptionPane.showMessageDialog(null, "Du musst in der Tabelle einen Kontakt zum bearbeiten auswählen.", "Fehler!", 1);
      }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
    {//GEN-HEADEREND:event_jButton3ActionPerformed
      try
      {
        oeffneKontakt("show", commonFunctions.markedElement.elementAt(jTable1.getSelectedRow()) );
      }
      catch (ArrayIndexOutOfBoundsException ex)
      {
        JOptionPane.showMessageDialog(null, "Du musst in der Tabelle einen Kontakt zum anzeigen auswählen.", "Fehler!", 1);
      }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton9ActionPerformed
    {//GEN-HEADEREND:event_jButton9ActionPerformed
      FilterDialog fd = new FilterDialog(this, false);
      fd.setVisible(true);
    }//GEN-LAST:event_jButton9ActionPerformed

    private void rechercheFlags()
    {
      int id = 0;
      try
      {
        if (selectedElement > -1)
        {
          id = commonFunctions.markedElement.elementAt(selectedElement);
          Statement stmt = con.createStatement();
          ResultSet rs1 = stmt.executeQuery(selectSQL + " where ID = " + id + order);
          rs1.next();

          int flags = rs1.getInt("VEREIN");

          if ( (flags & 1) == 1) //Forum Thomanum
            jCheckBox28.setSelected(true);
          else
            jCheckBox28.setSelected(false);

          if ( (flags & 4) == 4) //Förderkreis Thomanerchor
            jCheckBox29.setSelected(true);
          else
            jCheckBox29.setSelected(false);

          if ( (flags & 2) == 2) //Thomanerbund
            jCheckBox30.setSelected(true);
          else
            jCheckBox30.setSelected(false);

          if ( (flags & 8) == 8) //Freund des Chores
            jCheckBox31.setSelected(true);
          else
            jCheckBox31.setSelected(false);
          
          if ( (flags & 16) == 16) //Alumnus
            jCheckBox32.setSelected(true);
          else
            jCheckBox32.setSelected(false);

          rs1.close();
          stmt.close();

        }
      }
      catch (Exception e)
      {
        JOptionPane.showMessageDialog(null, "Beim Ausführen der Abfrage ist ein Fehler aufgetreten. Fehler:\r\n"
                + e.getLocalizedMessage(), "Fehler!", 1);
        e.printStackTrace();
        System.out.println(selectSQL + " where ID = " + id + order);
      }
    }

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTable1KeyPressed
    {//GEN-HEADEREND:event_jTable1KeyPressed
      refreshData();
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTable1MouseClicked
    {//GEN-HEADEREND:event_jTable1MouseClicked
      refreshData();
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton5ActionPerformed
    {//GEN-HEADEREND:event_jButton5ActionPerformed
      importDialog id = new importDialog(this, true);
      id.setVisible(true);
      while (id.isVisible())
      {
        try
        {
          Thread.sleep(250);
        }
        catch (InterruptedException iex)
        {
          //don't care
        }
      }
      commonFunctions.load_query_to_table(selectSQL, jTable1, mtm);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton7ActionPerformed
    {//GEN-HEADEREND:event_jButton7ActionPerformed
      try
      {
        History h = new History(commonFunctions.markedElement.elementAt(jTable1.getSelectedRow()));
        if (h.gibtKontakt)
          h.setVisible(true);
        else
          h.dispose();
      }
      catch (SQLException ex)
      {
        JOptionPane.showMessageDialog(null, "Zu diesem Eintrag gibt es keine History!",
                "Fehler!", JOptionPane.ERROR_MESSAGE);
      }
      catch (ArrayIndexOutOfBoundsException aibo)
      {
        JOptionPane.showMessageDialog(null, "Du musst in der Tabelle einen Kontakt auswählen.", "Fehler!", 1);
      }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton4ActionPerformed
    {//GEN-HEADEREND:event_jButton4ActionPerformed
      exportDialog ed = new exportDialog(this, true);
      ed.setVisible(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTable1KeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTable1KeyReleased
    {//GEN-HEADEREND:event_jTable1KeyReleased
      refreshData();
    }//GEN-LAST:event_jTable1KeyReleased

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem2ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem2ActionPerformed
      MailConfig mc = new MailConfig();
      mc.setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton6ActionPerformed
    {//GEN-HEADEREND:event_jButton6ActionPerformed
      Vector<String> anWen = new Vector<String>();

      for (int i = 0; i < jTable1.getRowCount(); i++)
      {
        Boolean b = (Boolean) jTable1.getModel().getValueAt(i, 0);
        if ( b.booleanValue() )
        {
          String an = mailString(i);
          if (an != null)
            anWen.add(an);
        }
      }
      //vielleicht ja auch nur der aktuell markierte?!?
      if ( anWen.size() == 0)
      {
        String an = mailString( jTable1.getSelectedRow() );
        if (an != null)
          anWen.add(an);
      }

      if ( anWen.size() > 0)
      {
        mailEditor me = new mailEditor(null, false, anWen);
        me.setVisible(true);
      }
    }//GEN-LAST:event_jButton6ActionPerformed

    private String mailString(int tableRowNum)
    {
      String an = "";
      if (tableRowNum >= 0)
      {
        String[] s = new String[]
        {
          (String) jTable1.getModel().getValueAt(tableRowNum, 13), //mail1
          (String) jTable1.getModel().getValueAt(tableRowNum, 14), //mail2
          (String) jTable1.getModel().getValueAt(tableRowNum, 25) //fa_mail
        };

        for (int j = 0; j < s.length; j++)
        {
          if ( commonFunctions.isValidMail(s[j]) )
          {
            an = s[j];
            break;
          }
        }
      }
      if ( an.length() > 0 )
        return an;
      else
        return null;
    }

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton8ActionPerformed
    {//GEN-HEADEREND:event_jButton8ActionPerformed
      for (int i = 0; i < jTable1.getRowCount(); i++)
        jTable1.getModel().setValueAt(Boolean.TRUE, i, 0);
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton10ActionPerformed
    {//GEN-HEADEREND:event_jButton10ActionPerformed
      for (int i = 0; i < jTable1.getRowCount(); i++)
        jTable1.getModel().setValueAt(Boolean.FALSE, i, 0);
    }//GEN-LAST:event_jButton10ActionPerformed

    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton11ActionPerformed
    {//GEN-HEADEREND:event_jButton11ActionPerformed
      String name = (String) jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 3) +
        (String) jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 3);
      Kontakthistorie kh = new Kontakthistorie(this, true,
        commonFunctions.markedElement.elementAt( jTable1.getSelectedRow() ), name);
      kh.setVisible(true);
    }//GEN-LAST:event_jButton11ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem3ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem3ActionPerformed
      DatabaseConfig dbc = new DatabaseConfig(this, true);
      dbc.setVisible(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowOpened
    {//GEN-HEADEREND:event_formWindowOpened
      // TODO add your handling code here:
    }//GEN-LAST:event_formWindowOpened

    private void refreshData()
    {
      selectedElement = jTable1.getSelectedRow();
      rechercheFlags();

      String[] ar = commonFunctions.getAendHinz(
              commonFunctions.markedElement.elementAt(jTable1.getSelectedRow()) );
      if (ar[1].length() > 0)
        jLabel1.setText( "Hinzugefügt: " + ar[1] );
      else
        jLabel1.setText( "Hinzugefügt: ");
      if (ar[0].length() > 0)
        jLabel2.setText( "Geändert: " + ar[0] );
      else
        jLabel2.setText( "Geändert: ");
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton10;
  private javax.swing.JButton jButton11;
  private javax.swing.JButton jButton2;
  private javax.swing.JButton jButton3;
  private javax.swing.JButton jButton4;
  private javax.swing.JButton jButton5;
  private javax.swing.JButton jButton6;
  private javax.swing.JButton jButton7;
  private javax.swing.JButton jButton8;
  private javax.swing.JButton jButton9;
  private javax.swing.JCheckBox jCheckBox28;
  private javax.swing.JCheckBox jCheckBox29;
  private javax.swing.JCheckBox jCheckBox30;
  private javax.swing.JCheckBox jCheckBox31;
  private javax.swing.JCheckBox jCheckBox32;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JMenu jMenu1;
  private javax.swing.JMenuBar jMenuBar1;
  private javax.swing.JMenuItem jMenuItem1;
  private javax.swing.JMenuItem jMenuItem2;
  private javax.swing.JMenuItem jMenuItem3;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JPanel jPanel2;
  private javax.swing.JPanel jPanel7;
  private javax.swing.JScrollPane jScrollPane1;
  public static javax.swing.JTable jTable1;
  private org.jdesktop.beansbinding.BindingGroup bindingGroup;
  // End of variables declaration//GEN-END:variables

}
